package com.pzh.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pzh.guli.service.edu.mapper.SubjectMapper;
import com.pzh.guli.service.edu.pojo.Subject;
import com.pzh.guli.service.edu.pojo.excel.ExcelSubject;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class ExcelSubjectListener extends AnalysisEventListener<ExcelSubject> {
    private SubjectMapper subjectMapper;
    @Override
    public void invoke(ExcelSubject data, AnalysisContext analysisContext) {
        log.info("解析到一条数据"+data);
        log.info("一级目录"+data.getLevelOneTitle());
        String levelOneTitle = data.getLevelOneTitle();
        String levelTowTile = data.getLevelTowTile();
        String parentId=null;
         //判断数据是否存在
        Subject byTitle = this.getByTitle(levelOneTitle);
        if (byTitle==null){
            Subject subject=new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);
            subjectMapper.insert(subject);
            Subject again = getByTitle(levelOneTitle);
            parentId=again.getId();
        }
        else {
            parentId=byTitle.getId();
        }
        //判断后面是否存在
        Subject two = this.getByTitle(levelTowTile, parentId);
        if (two==null){
            Subject subject=new Subject();
            subject.setTitle(levelTowTile);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
       log.info("剩余解析完成");
    }
    private Subject getByTitle(String title){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",title).eq("parent_id","0");
        return subjectMapper.selectOne(queryWrapper);
    }
    private Subject getByTitle(String title,String parentId){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",title).eq("parent_id",parentId);
        return subjectMapper.selectOne(queryWrapper);
    }
}
